package com.uchedao.seller.ui.car.blue_tooth;

import android.util.Log;

import com.cem.ictt.activities.car.ByteToString;
import com.uchedao.seller.module.DFEntity;
import com.uchedao.seller.util.ConversionUtil;
import com.uchedao.seller.util.LogUtil;


/**
 * DF-5000 数据传输协议
 * Created by zhengxizhen on 15/9/28.
 */
public class AnalyticalDFBlueTooth {

    private static String TAG = "AnalyticalDFBlueTooth";

    /**
     * 数据解析
     */
    public static DFEntity AnalyticalDF(byte[] readBuf) {
        DFEntity dfEntity = null;
        if (CalibrationData(readBuf)) {//校验
            Log.e(TAG, "CalibrationData校验成功");
            //解析数据
            ByteToString bts = new ByteToString();
            String[] array = bts.nativeByteString(readBuf);
            Float thickness = Float.parseFloat(array[0]);
            int integer = (int) (thickness * 10);
            dfEntity = new DFEntity();
            dfEntity.setType(0);
            dfEntity.setThickness(integer);
            LogUtil.e("===数据结果======" + array[0]);
            LogUtil.e("===物体类型======" + array[1]);
            LogUtil.e("===产品编号======" + array[2]);
            LogUtil.e("===产品批次======" + array[3]);
        } else {
            Log.e(TAG, "CalibrationData校验失败");
            dfEntity = null;
        }
        return dfEntity;
    }

    /**
     * 校验数据是否合法
     * 校验位是前面9个字节的累加和.
     */
    public static boolean CalibrationData(byte[] readBuf) {
        boolean result = false;
        try {
            int count = 0;
            int length = readBuf.length - 2;
            for (int i = 0; i < length; i++) {
                count += Integer.parseInt(Integer.toHexString(0xFF & readBuf[i]), 16);
            }
            //解析校验位
            String check16 = ConversionUtil.bytesToHexString(new byte[]{readBuf[length], readBuf[length + 1]});
            Log.e(TAG, check16);
            int check = Integer.parseInt(check16, 16);
            Log.e(TAG, "check=" + check + " \ncount=" + count);
            result = (check == count);
        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        } finally {
            return result;
        }
    }
}
